package com.chenfan.mcn.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chenfan.mcn.annotations.ActionTracing;
import com.chenfan.mcn.constant.NumberCst;
import com.chenfan.mcn.enums.ImportExcelEnum;
import com.chenfan.mcn.enums.OperateLockEnum;
import com.chenfan.mcn.extension.excel.ExcelHyperlinkDataHolder;
import com.chenfan.common.extension.lock.DistributedLockTemplate;
import com.chenfan.mcn.enums.StarTypeEnum;
import com.chenfan.mcn.exception.McnErrorCode;
import com.chenfan.mcn.extension.Res;
import com.chenfan.mcn.extension.excel.ExcelUtils;
import com.chenfan.common.extension.validation.groups.Add;
import com.chenfan.common.extension.validation.groups.Modify;
import com.chenfan.mcn.model.McnPage;
import com.chenfan.mcn.model.StarBasicData;
import com.chenfan.mcn.model.StarPlatformSettlementInfo;
import com.chenfan.mcn.model.dto.*;
import com.chenfan.mcn.model.vo.*;
import com.chenfan.mcn.service.StarBasicDataService;
import com.chenfan.mcn.service.StarPlatformInfoService;
import com.chenfan.mcn.utils.BusinessAssert;
import com.chenfan.mcn.utils.CommonUtil;
import com.chenfan.privilege.common.config.SearchAuthority;
import com.chenfan.privilege.common.config.UrlAuth;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 红人基础资料
 *
 * @Author liuyang
 * @Date 2021/1/7
 * @Time 18:59
 * @Version V1.0
 **/
@Slf4j
@RestController
@RequestMapping("/star/basic")
public class StarBasicDataController {

    @Autowired
    private StarBasicDataService starBasicDataService;

    @Autowired
    private StarPlatformInfoService starPlatformInfoService;

    /**
     * 红人资料列表
     *
     * @param page         请求参数
     * @param basicDataDto 请求参数
     * @return 返回值
     */
    @GetMapping(value = "/getList", produces = {"application/json;charset=UTF-8"})
    @UrlAuth({"basisFilesList_search"})
    public Res<Page<StarBasicDataVO>> getList(@ApiIgnore McnPage<StarBasicDataVO> page, @SearchAuthority(filterCustomer = false) StarBasicDataSearchDTO basicDataDto) {
        return Res.ok(starBasicDataService.getList(page, basicDataDto));
    }

    /**
     * 删除红人资料
     *
     * @param starId 请求参数
     * @return 返回值
     */
    @ActionTracing("删除红人")
    @GetMapping(value = "/del", produces = {"application/json;charset=UTF-8"})
    @UrlAuth({"basisFilesList_delete"})
    public Res<Object> del(Long starId) {
        return Res.ok(starBasicDataService.delete(starId));
    }

    /**
     * 启用禁用
     *
     * @param id         请求参数
     * @param starStatus 请求参数
     * @return 返回值
     */
    @ActionTracing("变更红人状态")
    @GetMapping(value = "/updateStatus", produces = {"application/json;charset=UTF-8"})
    public Res<Object> updateStatus(@RequestParam("id") Long id, @RequestParam("starStatus") Integer starStatus) {
        starBasicDataService.updateStatus(id, starStatus);
        return Res.ok();
    }

    /**
     * 红人平台结算信息的启用禁用
     * @param id
     * @param starStatus
     * @return
     */
    @ActionTracing("变更平台结算状态")
    @GetMapping(value = "/updatePlatformSettlementStatus", produces = {"application/json;charset=UTF-8"})
    public Res<Object> updatePlatformSettlementStatus(@RequestParam("id") Long id, @RequestParam("status") Integer starStatus) {
        starBasicDataService.updatePlatformSettlementStatus(id, starStatus);
        return Res.ok();
    }

    /**
     * 详情
     *
     * @param starId 请求参数
     * @return 返回值
     */
    @GetMapping(value = "/info", produces = {"application/json;charset=UTF-8"})
    public Res<StarBasicDataInfoVO> info(Long starId) {
        return Res.ok(starBasicDataService.info(starId));
    }

    /**
     * 导出列表数据
     *
     * @param basicDataDto 请求参数
     * @param response     请求参数
     */
    @GetMapping(value = "/export", produces = {"application/json;charset=UTF-8"})
    @UrlAuth({"basisFilesList_export"})
    public Res<Object> exportExcel(@SearchAuthority(filterCustomer = false) StarBasicDataSearchDTO basicDataDto, HttpServletResponse response) {
        try {
            ExcelUtils.exportExcel(CommonUtil.defaultList(starBasicDataService.exportExcel(basicDataDto, response)), "红人基础资料导出", StarBasicDataExportVO.class, "红人基础资料导出.xlsx", response);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Res.failed(McnErrorCode.FAILED);
        }
        return Res.ok();
    }

    /**
     * 红人执行单导出
     *
     * @param basicDataDto 请求参数
     * @param response     请求参数
     */
    @GetMapping(value = "/orderExport", produces = {"application/json;charset=UTF-8"})
    @UrlAuth({"basisFilesList_exportExecution"})
    public Res<Object> orderExportExcel(@SearchAuthority StarBasicDataSearchDTO basicDataDto, HttpServletResponse response) {
        try {
            starBasicDataService.exportExecuteOrderExcel(basicDataDto, response);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Res.failed(McnErrorCode.FAILED);
        }
        return Res.ok();
    }

    /**
     * 导出-红人平台信息
     *
     * @param basicDataDto 请求参数
     * @param response     请求参数
     */
    @GetMapping(value = "/exportPlatformInfo", produces = {"application/json;charset=UTF-8"})
    @UrlAuth({"basisFilesList_exportPlatformInfo"})
    public Res<Object> exportPlatformInfo(@SearchAuthority StarBasicDataSearchDTO basicDataDto, HttpServletResponse response) {
        try {
            starBasicDataService.exportPlatformInfo(basicDataDto, response);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Res.failed(McnErrorCode.FAILED);
        }
        return Res.ok();
    }


    /**
     * 新增红人基础资料
     *
     * @param starBasicDataDTO 请求参数
     * @return 返回值
     */
    @ActionTracing("新增红人")
    @PostMapping(value = "/save", produces = {"application/json;charset=UTF-8"})
    @UrlAuth({"basisFilesList_add"})
    public Res<Long> save(@Validated({Add.class}) @RequestBody StarBasicDataDTO starBasicDataDTO) {
        BusinessAssert.isTrue(StarTypeEnum.isInside(starBasicDataDTO.getStarType()), "非内部红人不允许新增！");
        return Res.ok(starBasicDataService.saveData(starBasicDataDTO));
    }

    /**
     * 修改红人基础资料
     *
     * @param starBasicDataDTO 请求参数
     * @return 返回值
     */
    @ActionTracing("修改红人")
    @PostMapping(value = "/update", produces = {"application/json;charset=UTF-8"})
    @UrlAuth({"basisFilesList_edit"})
    public Res<Long> update(@Validated({Modify.class}) @RequestBody StarBasicDataDTO starBasicDataDTO) throws Exception {
        BusinessAssert.isTrue(StarTypeEnum.isInside(starBasicDataDTO.getStarType()), "非内部红人不允许修改！");
        return Res.ok(DistributedLockTemplate.execute(OperateLockEnum.STAR_BASIC_DATA.generateKey(starBasicDataDTO.getId()),
                () -> starBasicDataService.updateData(starBasicDataDTO)));
    }


    /**
     * 红人执行单列表
     *
     * @param page   {@link McnPage}
     * @param starId {@link Long}
     * @return
     */
    @GetMapping(value = "/executions", produces = {"application/json;charset=UTF-8"})
    public Res<Page<StarExecutionVO>> executionList(@ApiIgnore McnPage<StarExecutionVO> page, Long starId) {
        return Res.ok(starBasicDataService.executionList(page, starId));
    }

    /**
     * 查询本平台对应的红人
     *
     * @param starType   红人类型，详见StarTypeEnum
     * @param starStatus 红人状态
     * @return
     */
    @GetMapping("/getAll")
    public Res<List<StarBasicDataInfoVO>> getAll(@RequestParam(required = false) Integer starType, @RequestParam(required = false) Integer starStatus) {
        List<StarBasicDataInfoVO> dataList = CommonUtil.defaultList(starBasicDataService.selectList(Wrappers.lambdaQuery(StarBasicData.class)
                .eq(starStatus != null, StarBasicData::getStarStatus, starStatus)
                .eq(starType != null, StarBasicData::getStarType, starType)
                .in(StarBasicData::getStarType, StarTypeEnum.getAllStarType())
                .eq(StarBasicData::getIsDelete, NumberCst.ZERO))).stream().map(e -> {
                    StarBasicDataInfoVO vo = new StarBasicDataInfoVO();
                    BeanUtils.copyProperties(e, vo);
                    return vo;
                }).collect(Collectors.toList());
        return Res.ok(dataList);
    }

    /**
     *
     * @param platformId
     * @return
     */
    @GetMapping("/getPlatSettlementsByPlatId")
    public Res<List<StarPlatformSettlementInfo>> getPlatSettlementsByPlatId(@RequestParam("platformId") Long platformId) {
        List<StarPlatformSettlementInfo> dataList = starBasicDataService.getPlatSettlementsByPlatId(platformId);
        return Res.ok(dataList);
    }

    /**
     * 批量导入更新平台（Excel文件）
     *
     * @param multipartFile
     * @return
     */
    @ActionTracing("导入-平台信息批量更新")
    @PostMapping("/importUpdatePlafromExcel")
    @UrlAuth({"basisFilesList_PlatformInformationImport"})
    public Res<String> importUpdatePlafromExcel(@RequestParam MultipartFile multipartFile) {
        List<StarPlatformInfoInputDTO> inputList = ExcelUtils.importExcel(multipartFile, StarPlatformInfoInputDTO.class);
        return Res.ok(starPlatformInfoService.importUpdatePlafromExcel(inputList));
    }

    /**
     * 下载批量批量导入更新平台-失败原因
     *
     * @param response
     * @param fileId   文件ID
     */
    @GetMapping("/download/updatePlafromFailedReason")
    public void downloadUpdatePlafromFailedReason(HttpServletResponse response, @RequestParam("fileId") String fileId) {
        log.error("下载批量批量导入更新平台-失败原因请求，fileId={}", fileId);
        BusinessAssert.isTrue(ImportExcelEnum.match(fileId, ImportExcelEnum.UPDATE_STAR_PLATFORM_INFO), McnErrorCode.EXPORT_FILE_ID_ILLEGAL);
        starPlatformInfoService.downloadUpdatePlafromFailedReason(response, fileId);
    }


    /**
     * 导入红人信息批量更新（Excel文件）
     *
     * @param multipartFile
     * @return
     */
    @ActionTracing("导入-红人信息批量更新")
    @PostMapping("/importExcel/updateStarBasicDataInfo")
    @UrlAuth({"basisFilesList_updateStarBasicDataInfo"})
    public Res<String> importStarBasicDataInfoExcel(@RequestParam MultipartFile multipartFile) {
        List<StarBasicDataInfoInputDTO> inputList = ExcelUtils.importExcel(multipartFile, StarBasicDataInfoInputDTO.class);
        return Res.ok(starBasicDataService.importStarBasicDataInfoExcel(inputList));
    }

    /**
     * 导出-签约合同信息
     *
     * @param basicDataDto 请求参数
     * @param response     请求参数
     */
    @UrlAuth({"basisFilesList_exportSignContract"})
    @GetMapping(value = "/exportSignContract", produces = {"application/json;charset=UTF-8"})
    public Res<Object> exportSignContract(@SearchAuthority StarBasicDataSearchDTO basicDataDto, HttpServletResponse response) {
        try {
            List<StarSignContractExportVO> exportData = starBasicDataService.exportSignContract(basicDataDto);
            ExcelUtils.exportExcel(CommonUtil.defaultList(exportData), "红人签约合同信息", StarSignContractExportVO.class, "红人签约合同信息.xlsx", response);
        } finally {
            ExcelHyperlinkDataHolder.clear();
        }
        return Res.ok();
    }
}
